from django.shortcuts import render
from django.http.response import HttpResponse
from PIL import Image, ImageDraw, ImageFont
from djang_ol.settings import *
from django.core.cache import cache
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import UserSerializer
import random,os,io
from md_shop.serializers import *
# Create your views here.

def generate_image_code(request, generate_image_id):
    '''
        本地图片验证码生成函数
    '''
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), random.randrange(20, 100))
    width = 110
    height = 40
    # 创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 定义验证码的备选值
    str = '1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str[random.randrange(0, len(str))]
    # 构造字体对象

    fonts_files = os.path.join(
        FONTS_DIRS, 'SourceCodePro-Bold.ttf')
    font = ImageFont.truetype(fonts_files, 30)
    # 构造字体颜色
    fontcolor1 = (255, random.randrange(0, 255), random.randrange(0, 255))
    fontcolor2 = (255, random.randrange(0, 255), random.randrange(0, 255))
    fontcolor3 = (255, random.randrange(0, 255), random.randrange(0, 255))
    fontcolor4 = (255, random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor1)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor2)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor3)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor4)
    # 释放画笔
    del draw
    # 存入缓存，用于做进一步验证，并设置超时时间为10分组
    cache.set(generate_image_id,rand_str,60*10)
    buf = io.BytesIO()
    # 将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    # 将内存中的图片数据返回给客户端，MIME类型为图片png！
    return HttpResponse(buf.getvalue(), 'image/png')

class CheckCodeView(APIView):
    def post(self, request):
        data = request.data
        sms_code = data["sms_code"]
        uuid_ = data["uuid_"]

        redis_code = cache.get(uuid_)

        if redis_code.lower() == sms_code.lower():
            return Response({"code":200})
        else:
            return Response({"code":500})

class UserRges(APIView):
    def post(self,request):
        ser = UserSer(data=request.data)
        res={}
        if ser.is_valid():
            res["code"] = 200
            res["msg"] = "注册成功"
        else:
            print(ser.errors)
            res["code"] = 500
            res["eroors"] = ser.errors
        return Response(res)




class CheckCode(APIView):
    def post(self,request):
        generate_image_id = request.data.get('generate_image_id',"")
        data_code = cache.get(generate_image_id)
        user_code = request.data.get('user_code',"")
        if data_code and user_code:
            print(data_code,user_code)
            if data_code.lower() == user_code.lower():
                return Response({'code':200})
        return Response({'code':201})



class UserView(APIView):
    def post(self,request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=200)
        return Response(serializer.errors, status=200)
